<?php

/*
	Class: WorkflowStatesContent

	About: Author
		Jaybill McCarthy

	About: License
		<http://communit.as/docs/license>


*/
class WorkflowStatesContent extends Workflow_Db_Table{

    protected $_name 	= 'workflow_states_content';
    protected $_primary = array('content_id','contenttype_id');

	function getCurrentStateId($content_id,$contenttype_id){
		$state = $this->fetchRow($this->select()->where("content_id = ?",$content_id)->where("contenttype_id = ?",$contenttype_id));
		if(!is_null($state)){
			return $state->state_id;
		} else {
			return "new";
		}			
	}
	
	function changeState($content_id,$contenttype_id,$state_id,$username,$state_set_on = null){		
		$itWorked = false;
		$content_types_table = new WorkflowContenttypes();		
		$statechanges_table = new WorkflowStatechanges();		
		$content_type = $content_types_table->getByContenttypeId($contenttype_id);
		
		$current_state_id = $this->getCurrentStateId($content_id,$contenttype_id);
		if(is_null($current_state_id)){
			$current_state_id = "new";			
		}
		if(!is_null($content_type)){
			$can_change = $statechanges_table->isChangeAllowed($content_id,$contenttype_id,$current_state_id,$state_id,$username);
			if($can_change){
							
				$data = array(
					'content_id' 			=> $content_id,
					'contenttype_id'		=> $contenttype_id,
					'state_id'				=> $state_id,
					'state_set_by_username'	=> $username,											
				);			
				
				$set_on_ts = null;
				
				if(!is_null($state_set_on)){					
					$data['state_set_on'] = date(DB_DATETIME_FORMAT,strtotime($state_set_on));
				} else {
					$data['state_set_on'] = date(DB_DATETIME_FORMAT);
				}
							
				if($current_state_id == "new"){			
					$this->insert($data);
				} else {
					$where 	= $this->getAdapter()->quoteInto("content_id = ? ",$content_id);
					$where .= $this->getAdapter()->quoteInto(" and contenttype_id = ? ",$contenttype_id);
					$this->update($data,$where);
				}
				$itWorked = true;
				$params = array(
					"content_id" 		=> $content_id,
					"contenttype_id" 	=> $contenttype_id,
					"state_id"			=> $state_id,
					"username"			=> $username,
					);
				Cts_Plugin::doAction("workflow_post_change_state",$params);							
			}	
		}
		
		return $itWorked;
	}
	
	
	
}
